package fr.anime.controller;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;

import javax.swing.tree.DefaultMutableTreeNode;

import fr.anime.model.Model;
import fr.anime.view.FilesView;

public class FilesViewController extends Controller {
	private Model model;
	private FilesView view;
	public FilesViewController(FilesView filesView, Model model) {
		// TODO Auto-generated constructor stub
		this.view = filesView;
		this.model = model;
		System.out.println("coucou filesviewcontroller");
		
		setDrives();
		
		view.getDriveSelection().addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				// TODO Auto-generated method stub
				System.out.println(view.getDriveSelection().getSelectedItem());
				setTree(view.getDriveSelection().getSelectedItem().toString());
			}

			
		});
	
		

	}
	
	private void setDrives() {
		view.getDriveSelection().removeAllItems();
		for (String string : model.getDrivesNames()) {
			view.getDriveSelection().addItem(string);
		}
	}
	
	private void setTree(Object selectedItem) {
		// TODO Auto-generated method stub
		model.setDrive(selectedItem);
		File files[] = model.getDrive().getFile().listFiles();
		
		DefaultMutableTreeNode treeRootDrive = new DefaultMutableTreeNode(selectedItem);
		for (File file : files) {
			if ((file.isDirectory()) && (!file.getName().equals("System Volume Information")) && (file.getName() != "RECYCLER") ) {
				System.out.println(file.getAbsolutePath());
			DefaultMutableTreeNode treeNodeFolder = new DefaultMutableTreeNode(file.getName());

		
			
			File subFiles[] = file.listFiles();
			for (File subFile : subFiles){
				DefaultMutableTreeNode treeChild = new DefaultMutableTreeNode(subFile.getName());
				treeNodeFolder.add(treeChild);
			}


			treeRootDrive.add(treeNodeFolder);

			}
			else {
				DefaultMutableTreeNode treeNodeFile = new DefaultMutableTreeNode(file.getName());
				treeRootDrive.add(treeNodeFile);
			}
		
		}
		
		view.buildTree(treeRootDrive);
	
	}

}
